//
//  HBOauthViewController.swift
//  sinaWeibo
//
//  Created by Beans on 16/6/24.
//  Copyright © 2016年 iceWorks. All rights reserved.
//

import UIKit

class HBOauthViewController: UIViewController,UIWebViewDelegate {

    // 定义属性
    let webView: UIWebView = UIWebView()

    override func loadView() {
        // web页面填充整个视图
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(AppRedirectURL)"
        let url = NSURL(string: urlString)!
        webView.loadRequest(NSURLRequest(URL: url))
        // 设置代理
        webView.delegate = self

        setupNav()
    }

    // MARK: - 设置导航栏
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autofill")
    }

    @objc private func dismiss() {
        dismissViewControllerAnimated(false) { () -> Void in
        }
    }

    @objc private func autofill() {
        // 引号的两种转换方式: 1> 转义; 2> " -> '
        let jsString = "document.getElementById('userId').value='\(userId)';document.getElementById('passwd').value='\(passWd)'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)

        // 此处要怎么去掉占位字符呢?
    }

    // MARK: - webViewDelegate 获取 code
    // 返回true, 则运行webView加载页面; false, 不允许加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        printLog(request.URL)

        // urlString是可选的, 可能为nil
        if let urlString = request.URL?.absoluteString {
            if urlString.hasPrefix(AppRedirectURL) {
                printLog("返回了code")
                printLog(urlString)

                // 获取code
                // 法一: 根据`=`截取
                // 法二: query
                /* For example, in the URL http://www.example.com/index.php?key1=value1&key2=value2, the query string is key1=value1&key2=value2. */
                if let queryStr = request.URL?.query {
                    let startIndex = "code=".endIndex
                    let code = queryStr.substringFromIndex(startIndex)
                    printLog(code)

                    /* 调用获取token的方法
                    1. 针对于成功的处理以及失败的处理,只集中在一处
                    2. 方法由谁创建,就由谁负责到底
                    */
                    let webSuccess = {
                        printLog("回调成功")
                        self.dismiss()
                        // MARK: - 视图控制器切换, 跳转到欢迎界面
                        // object
                        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationChangeRootVc, object: self)
                    }
                    let webFailure = {
                        printLog("请求失败")
                    }
                    HBOauthViewModel().loadToken(code, success: webSuccess, failure: webFailure)
                    return false // 返回false, 不让回调页面显示出来
                }
            }
        }

        return true
    }

    
}
